package cn.edu.hbpu.service.impl;

import cn.edu.hbpu.dto.LoginUser;
import cn.edu.hbpu.entity.User;
import cn.edu.hbpu.handler.CustomException;
import cn.edu.hbpu.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static cn.edu.hbpu.common.Constants.NONE_PROVIDED;

/**
 * @author lcy
 * @date 2022/8/4 8:17
 * @description
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 有时候前端没有传递用户名，此时用户名就是这个
        if (NONE_PROVIDED.equals(userName)) {
            throw new CustomException("用户名或密码错误");
        }

        // 1. 根据用户名查找用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, userName);
        User user = userMapper.selectOne(queryWrapper);
        // 2. 判断是否存在该用户
        if (Objects.isNull(user)) {
            throw new CustomException("用户名或密码错误");
        }

        // 3. 将用户信息封装并返回
        return new LoginUser(user);
    }
}
